//
//  MainViecwController.swift
//  YueJian
//
//  Created by mac on 2017/10/19.
//  Copyright © 2017年 MapleStory. All rights reserved.
//

import UIKit
import Alamofire

class MainViewController: UIViewController,UITableViewDelegate,UITableViewDataSource,UIScrollViewDelegate {
    
    let Width = UIScreen.main.bounds.width
    let scroller = UIScrollView()
    var pageCon:UIPageControl?
    var page = 0
    var array:[AnyObject]?
    var array0:[AnyObject]?
    var array2:[AnyObject]?
    var arrayScr:[AnyObject]?
    override func viewDidLoad() {
        super.viewDidLoad()

        self.title = "体育联盟"
        loadMasterData()
        loadScrollData()
        self.view.addSubview(segment)
        segment.addTarget(self, action: #selector(changTable(seg:)), for: UIControlEvents.valueChanged)
        self.view.addSubview(tableView)
    }
    
    func loadScrollData() {
        let sessionId = UserDefaults.standard.string(forKey: "sessionId")
        let params = ["SessionID":sessionId ?? "","posid":1,"related":1] as [String : Any]
        Alamofire.request(URL(string: RO_Scroll)!, method: .get, parameters: params, encoding: URLEncoding.default, headers: nil).responseJSON { (response) in
            self.arrayScr = response.result.value as? [AnyObject]
            self.initScrollView(array: self.arrayScr!)
        }
    }
    func initScrollView(array:[AnyObject]) {
        
        scroller.frame = CGRect(x: 0, y: 64, width: Width, height: 190)
        scroller.contentSize = CGSize(width: Width*CGFloat(array.count), height: 0)
        scroller.delegate = self
        scroller.isPagingEnabled = true
        scroller.isUserInteractionEnabled = true
        scroller.showsVerticalScrollIndicator = false
        scroller.showsHorizontalScrollIndicator = false
        for i in 0..<array.count {
            let imageView = UIImageView(frame: CGRect(x: CGFloat(i)*self.Width, y: 0, width: self.Width, height: 190))
            let dic = array[i] as! [String:AnyObject]
            let str = dic["thumb"] as! String
            let imageStr = "http://172.24.10.175/workout/Uploads/"+str
            let images = try! UIImage(data: Data(contentsOf: URL(string: imageStr)!))
            imageView.image = images
            imageView.isUserInteractionEnabled = true
            imageView.tag = i+100
            let tap = UITapGestureRecognizer(target: self, action: #selector(self.gowebview))
            imageView.addGestureRecognizer(tap)
            self.scroller.addSubview(imageView)
        }
        pageCon = UIPageControl(frame: CGRect(x: 135, y: 150+64, width: 100, height: 20))
        pageCon?.numberOfPages = array.count
        pageCon?.currentPage = 0
        self.view.addSubview(scroller)
        self.view.addSubview(pageCon!)
    
    }
    
    @objc func gowebview() {
    
        let dic = self.arrayScr![self.page] as! [String:AnyObject]
        let vc = WebViewController()
        vc.hidesBottomBarWhenPushed = true
        vc.dic = dic
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    private lazy var tableView: UITableView = {
        let table = UITableView(frame: CGRect(x: 0, y: 300, width: Screen_Width, height: Screen_Height-360), style: UITableViewStyle.plain)
        table.delegate = self
        table.dataSource = self
        table.register(UINib(nibName: "GameTableViewCell", bundle: nil), forCellReuseIdentifier: "reuseIdentifier")
        table.register(UITableViewCell.self, forCellReuseIdentifier: "cell1")
        table.register(UINib(nibName: "MasterTableViewCell", bundle: nil), forCellReuseIdentifier: "cell")
        return table
    }()

    private lazy var segment:UISegmentedControl = {
        let segment = UISegmentedControl(items: ["精彩活动","权威大师","最近比赛"])
        segment.frame = CGRect(x: 0, y: 260, width: Screen_Width, height: 30)
        segment.tintColor = UIColor.white
        segment.selectedSegmentIndex = 1
        return segment
    }()

    func loadMasterData() {
        let sessionId = UserDefaults.standard.string(forKey: "sessionId")
        Alamofire.request(URL(string: "http://172.24.10.175/workout/api.php/lists/mod/master")!, method: .get, parameters: ["SessionID":sessionId ?? ""], encoding: URLEncoding.default, headers: nil).responseJSON { (responcse) in
            self.array = responcse.result.value as? [AnyObject]
            self.tableView.reloadData()
        }
    }
 
    @objc func changTable(seg:UISegmentedControl) {
        if(segment.selectedSegmentIndex == 1) {
            loadMasterData()
        }
        if(segment.selectedSegmentIndex == 0) {
            let sessionId = UserDefaults.standard.string(forKey: "sessionId")
            Alamofire.request(URL(string: "http://172.24.10.175/workout/api.php/lists/mod/acmrecom")!, method: .post, parameters: ["SessionID":sessionId ?? "", "mod":"acmrecom","page":"1"], encoding: URLEncoding.default, headers: nil).responseJSON { (responcse) in
                print(responcse.result.value!)
                self.array0 = responcse.result.value as? [AnyObject]
                self.tableView.reloadData()
            }
        }
        if(segment.selectedSegmentIndex == 2) {
            let sessionId = UserDefaults.standard.string(forKey: "sessionId")
            Alamofire.request(URL(string: "http://172.24.10.175/workout/api.php/lists/mod/contest")!, method: .get, parameters: ["SessionID":sessionId ?? ""], encoding: URLEncoding.default, headers: nil).responseJSON { (responcse) in
                self.array2 = responcse.result.value as? [AnyObject]
                self.tableView.reloadData()
            }
        }
    }


    // MARK: - Table view data sourcecc

 
    func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

 
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        
        if(segment.selectedSegmentIndex == 1) {
            return array?.count ?? 0;
        } else if (segment.selectedSegmentIndex == 0) {
            return array0?.count ?? 0;
        } else {
            return array2?.count ?? 0;
        }
    }

    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if segment.selectedSegmentIndex == 1 {
            return 120
        }
        return 230
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if segment.selectedSegmentIndex == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath) as! GameTableViewCell
            let dic = array0?[indexPath.row] as! NSDictionary
            let num = dic["hits"] as! String
            cell.num = Int(num)!
            cell.number.text = num
            cell.title.text = dic["rec_name"] as? String
            let str = dic["thumb"] as! String
            let imageStr = "http://172.24.10.175/workout/Uploads/"+str
                do {
                    let images = try UIImage(data: Data(contentsOf: URL(string: imageStr)!))
                    cell.imageview.image = images
                }catch{
                    cell.backgroundView = UIImageView(image: UIImage(named: "scroller0"))
                }
            cell.selectionStyle = .none
            return cell
        } else if segment.selectedSegmentIndex == 1 {
            let dic = array?[indexPath.row] as! NSDictionary
            let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! MasterTableViewCell
            let str = dic["thumb"] as! String
            let imageStr = "http://172.24.10.175/workout/Uploads/"+str
            let images = try! UIImage(data: Data(contentsOf: URL(string: imageStr)!))
            cell.head.image = images
            cell.head.layer.cornerRadius = 50
            cell.head.clipsToBounds = true
            let actcate_name = dic["actcate_name"] as!String
            let realname = dic["realname"] as!String
            cell.title.text = actcate_name + realname
            cell.num = dic["hits"] as?String
            cell.number.text = dic["hits"] as?String
            return cell
        } else {
            let dic = array2?[indexPath.row] as! NSDictionary
            let cell = tableView.dequeueReusableCell(withIdentifier: "cell1", for: indexPath)
            let str = dic["thumb"] as! String
            let imageStr = "http://172.24.10.175/workout/Uploads/"+str
            let images = try! UIImage(data: Data(contentsOf: URL(string: imageStr)!))
            cell.backgroundView = UIImageView(image: images)
            cell.selectionStyle = .none
            return cell
        }
        
    }
    
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    
        switch segment.selectedSegmentIndex {
        case 0:
            let vc = ClubDetailViewController()
            let dic = array0?[indexPath.row] as? [String:AnyObject]
            vc.hidesBottomBarWhenPushed = true
            vc.id = dic?["id"] as? String ?? ""
            self.navigationController?.pushViewController(vc, animated: true)
        case 1:
            let vc = MasterTableViewController()
            let dic = array?[indexPath.row] as? [String:AnyObject]
            vc.hidesBottomBarWhenPushed = true
            vc.title = "大师"
            vc.masterId = dic?["id"] as? String ?? ""
            self.navigationController?.pushViewController(vc, animated: true)
        default:
            let vc = WebViewController()
            vc.title = "冠军"
            vc.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(vc, animated: true)
        }
        
    }
    
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        self.page = Int(scrollView.contentOffset.x/Screen_Width)
        pageCon?.currentPage = page

    }


}
